package com.yilei.testninegridview

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.ext.SdkExtensions
import android.provider.MediaStore
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView


class NineGridView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    val PICK_IMAGE_MULTIPLE: Int = 1
    private val recyclerView: RecyclerView
    private val adapter: NineGridAdapter
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent>

    init {
        // Inflate the layout
        val view = LayoutInflater.from(context).inflate(R.layout.view_nine_grid, this, true)
        recyclerView = view.findViewById(R.id.recyclerView)

        // Initialize the adapter with default callbacks
        adapter = NineGridAdapter(mutableListOf(),
            onImageClick = { position ->

            },
            onAddImageClick = {

                val mimeType = "image/*"
                pickMedia.launch(
                    PickVisualMediaRequest(
                        ActivityResultContracts.PickVisualMedia.SingleMimeType(
                            mimeType
                        )
                    )
                )

            }
        )

        recyclerView.layoutManager = GridLayoutManager(context, 3)
        val spacingInPixels = 10 // 从 dimens.xml 获取间隙值
        recyclerView.addItemDecoration(ItemDecoration(3, spacingInPixels))
        recyclerView.adapter = adapter
    }

    fun setImageUrls(urls: List<String>) {
        adapter.updateImageUrls(urls)
    }

    //
    fun setOnImageClickListener(listener: (Int) -> Unit) {
        //adapter.setOnImageClickListener(listener)
    }

    /**
     * PickMultipleVisualMedia(num) 多选
     * block()在调用位置写获取图片uri后的操作
     */
    fun setupMediaPicker(
        context: FragmentActivity,
        block: (uri: Uri?) -> Unit
    ) {
        this.pickMedia =
            context.registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                //在用户选择媒体项目或关闭照片选择器后调用回调。
                block(uri)
            }

    }
//
//    fun setOnAddImageClickListener(listener: () -> Unit) {
//        adapter.setOnAddImageClickListener(listener)
//    }
}
